package com.icw.decoupling.impl.tool;

import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.icw.decoupling.defi.tool.DataExchange;
import com.icw.utility.JsonUtils;
import com.icw.utility.PoEntityHelper;

@Component
public class JsonDataExchange implements DataExchange {

	@Override
	public String serialize(Object o) throws Exception {
		return JsonUtils.serialize(o);
	}

	@Override
	public <T> T parse(Object source, Class<T> clazz) throws Exception {
		T res;
		if (String.class.isInstance(source)) {
			res = JsonUtils.deserialize((String) source, clazz);
		} else {
			res = JsonUtils.deserialize(source, clazz);
		}
		return res;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> parseMap(Object source) throws Exception {
		return parse(source, Map.class);
	}

	@Override
	public Collection<Object> parseCollection(Object source) throws Exception {
		Collection<Object> list = new LinkedList<>();
		JSONArray res;
		if (String.class.isInstance(source)) {
			res = JsonUtils.deserialize((String) source, JSONArray.class);
		} else {
			res = JsonUtils.deserialize(source, JSONArray.class);
		}
		Object[] objects = PoEntityHelper.toObjectArray(res);
		for (Object obj : objects) {
			list.add(parse(obj, null));
		}
		return list;
	}
}
